package com.cnzha.zk;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author: zhaoxin
 * @email: zdkk@foxmail.com
 * @Date: 2020/4/7 22:59
 */
public class ZkTest {

    public static final String clust = "hadoop102:2181,hadoop103:2181,hadoop104:2181";
    public static final int sessionTimeOut = 2000;
    private ZooKeeper zooKeeper;

    @Before
    public void init() throws IOException {
        zooKeeper = new ZooKeeper(clust, sessionTimeOut, (watchedEvent) -> {
            //process回调
            Watcher.Event.EventType type = watchedEvent.getType();
            String path = watchedEvent.getPath();
            System.out.println("path = " + path);
            System.out.println("type = " + type);
            //再次启动监听
            try {
                zooKeeper.getChildren("/", true);
            } catch (KeeperException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }

    @Test
    public void create() throws KeeperException, InterruptedException {
        String s = zooKeeper.create("/zhaoxin", "dake".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        System.out.println("s = " + s);
    }

    @Test
    public void getChildren() throws KeeperException, InterruptedException {
        List<String> children = zooKeeper.getChildren("/", true);
        for (String child : children) {
            System.out.println("child = " + child);
        }
        TimeUnit.SECONDS.sleep(Long.MAX_VALUE);
    }

    // 判断znode是否存在
    @Test
    public void exist() throws Exception {
        Stat stat = zooKeeper.exists("/eclipse", false);
        System.out.println(stat == null ? "not exist" : "exist");
    }


}
